package xidian.vlab.service.impl;

import org.openstack4j.api.Builders;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.common.Identifier;
import org.openstack4j.model.common.Payload;
import org.openstack4j.model.common.Payloads;
import org.openstack4j.model.image.v2.ContainerFormat;
import org.openstack4j.model.image.v2.DiskFormat;
import org.openstack4j.model.image.v2.Image;
import org.openstack4j.openstack.OSFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xidian.vlab.config.Properties;
import xidian.vlab.domin.Log;
import xidian.vlab.domin.User.Teacher;
import xidian.vlab.dto.*;
import xidian.vlab.repository.User.TeacherRepository;
import xidian.vlab.service.StackService;
import xidian.vlab.utils.ResUtil;
import org.openstack4j.api.OSClient.OSClientV3;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("StackService")
public class StackServiceImpl implements StackService {
    @Autowired
    private TeacherRepository tchRepo;
    @Autowired
    private Properties properties;

    @Override
    public ResJsonDTO getHost(QueryDTO query){
        ListDTO list = new ListDTO();

        return ResUtil.OK(list);
    }

    @Override
    public ResJsonDTO getImages(QueryDTO query){
        if (query.getTid() == null) {// fixme: 管理员获取镜像
            return ResUtil.ERROR("query error, teacher id is null!");
        }
        Teacher teacher = tchRepo.findById(query.getTid()).orElse(null);
        if (teacher == null) {
            return ResUtil.ERROR("未找到该用户:"+query.getTid());
        }

        OSClientV3 os = OSFactory.builderV3()
                .endpoint(properties.getKeystoneAPI())
                .credentials(teacher.getUserID(),teacher.getPassword())
                .scopeToProject(Identifier.byId(teacher.getProjectID()))
                .authenticate();

        ListDTO list = new ListDTO();
        List<ImageDTO> imgList = new ArrayList<>();
        List<? extends Image> images = os.imagesV2().list();
        for (Image image : images) {
            Teacher owner = tchRepo.findByProjectID(image.getOwner());//根据ID获取姓名
            imgList.add(new ImageDTO(
                    image.getId(),
                    owner == null ? "管理员" : owner.getName(),
                    image.getName(),
                    image.getDiskFormat(),
                    image.getSize()
            ));
        }

        list.setImageList(imgList);
        list.setTotal(imgList.size());
        // fixme: 日志记录操作人
        System.out.println("管理员["+query.getAid()+"]获取镜像列表成功");
        return ResUtil.OK(list);
    }
    @Override
    public ResJsonDTO uploadImage(ImageDTO imageForm){
        if (imageForm.getFile().isEmpty()) {
            return ResUtil.ERROR("镜像文件为空!");
        }
        Teacher teacher = tchRepo.findById(imageForm.getTid()).orElse(null);
        if (teacher == null) {
            return ResUtil.ERROR("未找到该用户:"+imageForm.getTid());
        }

        try {
            final File tmpImageFile = File.createTempFile("imageFile","img");
            imageForm.getFile().transferTo(tmpImageFile);

            OSClientV3 os = OSFactory.builderV3()
                    .endpoint(properties.getKeystoneAPI())
                    .credentials(teacher.getUserID(),teacher.getPassword())
                    .scopeToProject(Identifier.byId(teacher.getProjectID()))
                    .authenticate();
            Image image = os.imagesV2().create(
                    Builders.imageV2()
                            .name(imageForm.getImgName())
                            .containerFormat(ContainerFormat.BARE)
                            .visibility(Image.ImageVisibility.PRIVATE)
                            .diskFormat(imageForm.getFormat())
                            .minDisk(0L)
                            .minRam(0L)
                            .build()
            );
            Payload<File> payload = Payloads.create(tmpImageFile);
            ActionResponse upload = os.imagesV2().upload(
                    image.getId(),
                    payload,
                    image);

            tmpImageFile.delete();// fixme: remove warning

            if (upload.isSuccess()) {
                return ResUtil.OK();
            } else {
                return ResUtil.ERROR("上传镜像失败!");
            }

        }catch (IOException e) {
            e.printStackTrace();
            return ResUtil.ERROR("服务器内部错误!");
        }

    }
    @Override
    public ResJsonDTO deleteImage(QueryDTO query){
        Teacher teacher = tchRepo.findById(query.getTid()).orElse(null);
        if (teacher == null) {
            return ResUtil.ERROR("该用户不存在:"+query.getTid());
        }

        OSClientV3 os = OSFactory.builderV3()
                .endpoint(properties.getKeystoneAPI())
                .credentials(teacher.getUserID(),teacher.getPassword())
                .scopeToProject(Identifier.byId(teacher.getProjectID()))
                .authenticate();
        os.imagesV2().delete(query.getImgId());

        return ResUtil.OK();
    }

//    @Override
//    public Server createVM(String student, String image){
//        ServerCreate sc = Builders.server()
//                .name(student)
//                .flavor("2cbaeadf3a084f97acb10613b93a2de6")
//                .image(image)
//                .addPersonality("/etc/motd", "Welcome to the new VM! Restricted access only")
//                .build();
//        Server server = os.compute().servers().boot(sc);
//        os.compute().floatingIps().allocateIP("pool");
//        os.compute().servers().action(server.getId(), Action.STOP);
//        return server;
//    }
}
